/*****************************************************************************/
/*                                                                           */
/*    Domino Operation System Driver Module                                  */
/*                                                                           */
/*    Copyright (C) 2008 Laszlo Arvai                                        */
/*                                                                           */
/*    ------------------------------------------------------------------     */
/*    ADC Driver for PIC32 series                                            */
/*****************************************************************************/

///////////////////////////////////////////////////////////////////////////////
// Includes
#include <drvADC.h>
#include "drvIOConfig.h"

///////////////////////////////////////////////////////////////////////////////
// Module Global variables
static dosWord l_avg_counter = 0;
static dosDWord l_avg = 0;
dosWord g_internal_ad_value = 0;

///////////////////////////////////////////////////////////////////////////////
// Initialize ADC driver
void drvADCInit(void)
{
	// define setup parameters for OpenADC10
	#define PARAM1  ADC_MODULE_ON | ADC_FORMAT_INTG | ADC_CLK_AUTO | ADC_AUTO_SAMPLING_ON

	// define setup parameters for OpenADC10
	#define PARAM2  ADC_VREF_AVDD_AVSS | ADC_OFFSET_CAL_DISABLE | ADC_SCAN_OFF | ADC_SAMPLES_PER_INT_1

	// define setup parameters for OpenADC10
	#define PARAM3  ADC_CONV_CLK_INTERNAL_RC | ADC_SAMPLE_TIME_15

	// define setup parameters for OpenADC10
	#define PARAM4 ADC_CHANNEL_ENABLE

	// define setup parameters for OpenADC10
	#define PARAM5 SKIP_SCAN_ALL

	// configure ADC
	SetChanADC10( ADC_CH0_NEG_SAMPLEA_NVREF | ADC_SET_CHANNEL );

  // configure ADC using parameter define above
  OpenADC10( PARAM1, PARAM2, PARAM3, PARAM4, PARAM5 );

	// -- configure the ADC interrupt, priority level 2 --
  // NOTE: the C32 compiler manual uses ADC_INT_ENABLE for the enable flag
  //       this is wrong, use ADC_INT_ON / ADC_INT_OFF
  ConfigIntADC10(ADC_INT_PRI_2 | ADC_INT_SUB_PRI_2 | ADC_INT_ON);

  // clear the interrupt flag 
  mAD1ClearIntFlag();

  // Enable the ADC
  EnableADC10();
}

///////////////////////////////////////////////////////////////////////////////
// ADC Interrupt handler
// Specify ADC Interrupt Routine, Priority Level = 2
void __ISR(_ADC_VECTOR, ipl2) _ADC_Handler(void)
{
  // clear the interrupt flag
  mAD1ClearIntFlag();

  // the results of the conversions are available in channel4 and channel5
  l_avg += ReadADC10(0);
  
  l_avg_counter++;
  if( l_avg_counter == 1024 * 32 )
  {
	 	l_avg_counter = 0;
	 	g_internal_ad_value = l_avg >> 10;
	 	l_avg = 0;
	} 
}


